//
//  WBUserAceeessModel.swift
//  WB
//
//  Created by macssss on 16/7/4.
//  Copyright © 2016年 macssss. All rights reserved.
//

import UIKit

private let accounFile: NSString  = "useraccount.json"

//MARK: - 用户模型
class WBUserAceeessModel: NSObject {

    //用户访问令牌
    
    var access_token: String?
    //= "2.00Ecu31E0QwB8c3cc9495ed0wAWGqC"
    //用户Id
    var uid: String?
    /// access_token的生命周期，单位是秒数
    /// 开发者 5 年
    /// 使用者 3 天
    var expires_in: TimeInterval = 0 {
        
        didSet {
            
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }

    //过期日期
    var expiresDate: Date?
    
    //用户昵称
    var screen_name: String?
    //用户头像地址
    var avatar_large: String?
    
    override var description: String {
        
        return yy_modelDescription()
        
    }
    
    
    override init() {
        
        super.init()
        
        guard let path = accounFile.cz_appendDocumentDir(),
                data = NSData(contentsOfFile: path),
            dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String : AnyObject]
            else {
            return
        }
        
        //FIXME: -  用户登录关键代码
        yy_modelSet(with: dict ?? [:])
        
        print("从沙盒加载用户数据\(self)")
       // FIXME: 延时时间 测试taken过期
//        expiresDate = NSDate(timeIntervalSinceNow: -3600 * 24 * 365 * 20) as Date
        
        if expiresDate?.compare(Date()) != .orderedDescending {
            
            print("账户过期")
            //清空用户信息
            access_token = nil
            uid = nil 
            
            //删除用户文件
          _ = try? FileManager.default.removeItem(atPath: path)
            
        }
        
    }
    
    /**
     1. 偏好设置(小) - Xcode 8 beta 无效！
     2. 沙盒- 归档／plist/json
     3. 数据库(FMDB/CoreData)
     4. 钥匙串访问(小／自动加密 - 需要使用框架 SSKeychain)
     */
    //MARK: -  用户信息储存
    func saveAccess() {
        
        var dict = (self.yy_modelToJSONObject() as? [String : AnyObject]) ?? [:]
        
        dict.removeValue(forKey: "expires_in")
        
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            
                filePath = accounFile.cz_appendDocumentDir()
        
             else {
            
                return
        }
        
        print(filePath)
        
        (data as NSData).write(toFile: filePath, atomically: true)
    }


}
